package cn.xeblog.server.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.lang.ConsoleTable;
import cn.hutool.json.JSONUtil;
import cn.xeblog.commons.entity.XEUser;
import cn.xeblog.server.cache.RedisCache;
import cn.xeblog.server.config.ServerConfig;
import lombok.SneakyThrows;
import redis.clients.jedis.Jedis;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 功能描述:
 *
 * @author ZhangLei
 * @date 2023/2/28 9:37
 */
public class Test {


    /*
        丐版狼人杀思路
        身份：平民、狼人、预言家、女巫、猎人
        大致流程：
            ①玩家就位，系统随机发身份

        ---循环---
            ②天黑 系统计时
               时间段1 ： 狼人动：刀人（系统标记人物死亡） |  预言家：查验人身份
               时间段2 ： 系统告知女巫人物死亡，使用药瓶
               ④系统根据存活玩家判断游戏是否结束
            ③天亮 系统计时
                时段1：玩家在聊天框畅所欲言 （后续可升级为轮流发言）
                时段2：计时结束进行投票（系统标记人物死亡）
                ④系统根据存活玩家判断游戏是否结束
        ---循环---

            ⑤游戏结束：公开各玩家身份
     */

    public static void main(String[] args) {


    }

    public static void showCommonUser() {
        ServerConfig serverConfig = ConfigUtil.readConfig(null);
        ServerConfig.setServerConfig(serverConfig);
        RedisCache redisCache = new RedisCache(serverConfig.getRedisHost(), serverConfig.getRedisPort(), serverConfig.getRedisPassword(), 1);
        Jedis jedis = redisCache.getJedis();

        Map<String, String> nameCache = jedis.hgetAll(RedisCache.USER_NAME_CACHE);

        List<XEUser> xeUserList = nameCache.keySet().stream().map(k -> JSONUtil.parseObj(nameCache.get(k)).toBean(XEUser.class)).collect(Collectors.toList());
        Map<String, List<XEUser>> groupMap = xeUserList.stream().collect(Collectors.groupingBy(XEUser::getUuid));

        Console.log("\n============================== {} ==============================", "UUID一样的用户");
        groupMap.forEach((uuid, l) -> {
            if (l.size() > 1) {
                Console.log("====================== {} ======================", uuid);
                showTable(l);
            }
        });

        Map<String, String> uuidCache = jedis.hgetAll(RedisCache.USER_CACHE);
        List<XEUser> lost = xeUserList.stream().filter(u -> !uuidCache.containsKey(u.getUuid())).collect(Collectors.toList());
        Console.log("\n============================== {} ==============================", "USER_CACHE里面没有的用户");
        showTable(lost);
    }

    public static void showTable(List<XEUser> xeUserList) {
        if (CollectionUtil.isEmpty(xeUserList)) {
            return;
        }

        ConsoleTable consoleTable = ConsoleTable.create();
        consoleTable.addHeader("username", "region", "UUID");
        xeUserList.forEach(xeUser -> consoleTable.addBody(xeUser.getUsername(), xeUser.getRegion(), xeUser.getUuid()));
        consoleTable.print();
    }

    public static String getMac() {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                byte[] bytes = networkInterface.getHardwareAddress();
                if (bytes != null) {
                    StringBuilder sb = new StringBuilder();
                    for (byte b : bytes) {
                        sb.append(String.format("%02X", b)).append("-");
                    }
                    sb.deleteCharAt(sb.length() - 1);
                    return sb.toString();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @SneakyThrows
    public static void showNetwork() {
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            System.out.println("设备在操作系统中显示的名称: " + networkInterface.getDisplayName());
            System.out.println("网络设备在操作系统中的名称: " + networkInterface.getName());
            System.out.println("网络接口是否已经开启并正常工作: " + networkInterface.isUp());
            System.out.println("网络接口的最大传输单元(MTU): " + networkInterface.getMTU());
            System.out.println("网络接口是是否是环回接口: " + networkInterface.isLoopback());
            Enumeration<InetAddress> inetAddressesList = networkInterface.getInetAddresses();
            System.out.print("网络接口的硬件地址(MAC地址): ");
            byte[] hardwareAddress = networkInterface.getHardwareAddress();
            if (hardwareAddress != null && hardwareAddress.length > 0) {
                System.out.println(bytesToHexMac(hardwareAddress));
            } else {
                System.out.println(Arrays.toString(networkInterface.getHardwareAddress()));
            }
            while (inetAddressesList.hasMoreElements()) {
                InetAddress address = inetAddressesList.nextElement();
                System.out.println("主机地址: " + address.getHostAddress());
            }

            System.out.println("=============分隔=============");
        }
    }

    public static String bytesToHexMac(byte[] bytes) {
        StringBuilder buf = new StringBuilder(bytes.length * 2);
        for (int i = 0; i < bytes.length; i++) {
            buf.append(String.format("%02x", bytes[i] & 0xff));
            if (i != bytes.length - 1) {
                buf.append(":");
            }
        }
        return buf.toString();
    }


}
